<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/30
 * Time: 15:31
 */

namespace app\api\controller\v1;


use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\model;
use app\common\lib\exception\ApiException;

/**
 * 客户端 auth 登录权限基础类库
 * 1、每个接口（需要登录 个人中心 点赞 评论）都需要去集
 * 2、判定 access_user_token 是否合法
 * Class AuthBase
 * @package app\api\controller\v1
 */
class AuthBase extends Common
{

    /**
     * 登录用户的基本信息
     * @var array
     */
    public $user = [];

    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        if ($this->isLogin()){
            throw new ApiException('您没有登录', 403);
        }

    }

    /**
     * 判断用户登录
     * @return bool
     */
    public function isLogin(){
        if (empty($this->headers['access_user_token'])){
            return false;
        }

        //正式环境 access_user_token 需要加密解密

        $obj = new Aes();
        $accessUserToken = $obj->decrypt($this->headers['access_user_token']);
        if (empty($accessUserToken)){
            return false;
        }

        if (!preg_match('/||/'. $accessUserToken)){
            return false;
        }
        list($token, $id) = explode("||", $accessUserToken);
        $user = model\User::get(['token' => $token]);

        if (!$user || $user->status != config('code.status_normal')){
            return false;
        }
        //判定时间是否过期
        if (time() > $user->time_out){
            return false;
        }

        $this->user = $user;
        return true;
    }

}